import picker from '@ohos.file.picker';
import fs from '@ohos.file.fs';
import { Log } from './log';
import image from '@ohos.multimedia.image';

/**
 * 选择图片
 * @param max
 * @returns
 */
export async function selectImage(max?: number): Promise<string[]> {
  const photoSelectOptions = new picker.PhotoSelectOptions();
  photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
  photoSelectOptions.maxSelectNumber = max ? max : 1; // 选择媒体文件的最大数目
  const photoViewPicker = new picker.PhotoViewPicker();
  try {
    let photoSelectResult = await photoViewPicker.select(photoSelectOptions);
    return photoSelectResult.photoUris;
  } catch (err) {
    Log.error(`调用photoViewPicker选择图片发生异常，code is ${err.code}, message is ${err.message}`)
  }
}

/**
 * 读取文件
 * @param uri
 * @returns
 */
export function readFile(uri: string): ArrayBuffer {
  let file
  try {
    file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
    let stat = fs.statSync(file.fd);
    let buffer = new ArrayBuffer(stat.size);
    fs.readSync(file.fd, buffer);
    return buffer;
  } catch (err) {
    Log.error('读取文件发生异常', err)
  } finally {
    if (file) {
      fs.close(file);
    }
  }
}

/**
 * 根据文件描述符获取位图
 * @param fd
 * @returns
 */
export async function getPixelMap(fd: number) {
  const imageSourceApi = image.createImageSource(fd);
  if (!imageSourceApi) {
    Log.error('imageSourceAPI created failed!');
    return;
  }
  const pixelMap = await imageSourceApi.createPixelMap({
    editable: true
  });
  return pixelMap;
}